package com.example.mydy;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mydy.model.UserInfo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class SimulationManagementActivity extends AppCompatActivity {

    private EditText etUserSearch;
    private Button btnSearchUser;
    private RecyclerView rvUserList;
    private TextView tvSelectedUser, tvUserStatus, tvUserRewardInfo, tvSimulationResult;
    private Button btnCompleteTask;

    private UserAdapter userAdapter;
    private List<UserInfo> userList = new ArrayList<>();
    private UserInfo selectedUser = null;

    // 模拟任务和邀请奖励设置
    private float globalTaskReward = 1.0f;
    private float globalInviteReward = 1.0f;
    private float taskL1Ratio = 50.0f;
    private float taskL2Ratio = 30.0f;
    private float taskL3Ratio = 10.0f;
    private float inviteL1Ratio = 50.0f;
    private float inviteL2Ratio = 30.0f;
    private float inviteL3Ratio = 10.0f;
    private boolean taskRewardEnabled = true;
    private boolean inviteRewardEnabled = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simulation_management);

        // 初始化视图
        initViews();
        // 初始化模拟数据
        loadMockData();
        // 设置监听器
        setupListeners();
        // 初始化RecyclerView和适配器
        setupRecyclerView();
    }

    private void initViews() {
        etUserSearch = findViewById(R.id.et_user_search);
        btnSearchUser = findViewById(R.id.btn_search_user);
        rvUserList = findViewById(R.id.rv_user_list);
        tvSelectedUser = findViewById(R.id.tv_selected_user);
        tvUserStatus = findViewById(R.id.tv_user_status);
        tvUserRewardInfo = findViewById(R.id.tv_user_reward_info);
        btnCompleteTask = findViewById(R.id.btn_complete_task);
        tvSimulationResult = findViewById(R.id.tv_simulation_result);
    }

    private void loadMockData() {
        // 从应用中加载全局奖励设置
        loadGlobalRewardSettings();
        
        // 模拟用户数据
        createMockUsers();
    }

    private void loadGlobalRewardSettings() {
        // 在实际应用中，这应该从TaskRewardActivity的共享首选项中加载
        // 这里使用默认值模拟
        taskRewardEnabled = true;
        inviteRewardEnabled = true;
        globalTaskReward = 1.0f;
        globalInviteReward = 1.0f;
        taskL1Ratio = 50.0f;
        taskL2Ratio = 30.0f;
        taskL3Ratio = 10.0f;
        inviteL1Ratio = 50.0f;
        inviteL2Ratio = 30.0f;
        inviteL3Ratio = 10.0f;
    }

    private void createMockUsers() {
        // 创建一个用户层级结构
        // A -> B -> C -> D (A是B的上级，B是C的上级，C是D的上级)
        
        // 用户A（特权用户）
        UserInfo userA = new UserInfo();
        userA.setId(1);
        userA.setUsername("userA");
        userA.putExtra("is_privilege", "true");
        userA.putExtra("task_reward", "10");
        userA.putExtra("invite_reward", "5");
        userA.putExtra("level1_ratio", "70");
        userA.putExtra("level2_ratio", "40");
        userA.putExtra("level3_ratio", "20");
        userA.putExtra("invite_level1_ratio", "70");
        userA.putExtra("invite_level2_ratio", "40");
        userA.putExtra("invite_level3_ratio", "20");
        userA.putExtra("balance", "100");
        
        // 用户B（普通用户）
        UserInfo userB = new UserInfo();
        userB.setId(2);
        userB.setUsername("userB");
        userB.putExtra("parent_id", "1"); // A是B的上级
        userB.putExtra("balance", "50");
        
        // 用户C（特权用户）
        UserInfo userC = new UserInfo();
        userC.setId(3);
        userC.setUsername("userC");
        userC.putExtra("is_privilege", "true");
        userC.putExtra("parent_id", "2"); // B是C的上级
        userC.putExtra("task_reward", "5");
        userC.putExtra("invite_reward", "3");
        userC.putExtra("level1_ratio", "60");
        userC.putExtra("level2_ratio", "35");
        userC.putExtra("level3_ratio", "15");
        userC.putExtra("invite_level1_ratio", "60");
        userC.putExtra("invite_level2_ratio", "35");
        userC.putExtra("invite_level3_ratio", "15");
        userC.putExtra("balance", "80");
        
        // 用户D（普通用户）
        UserInfo userD = new UserInfo();
        userD.setId(4);
        userD.setUsername("userD");
        userD.putExtra("parent_id", "3"); // C是D的上级
        userD.putExtra("balance", "30");
        
        // 添加到用户列表
        userList.add(userA);
        userList.add(userB);
        userList.add(userC);
        userList.add(userD);
    }

    private void setupListeners() {
        btnSearchUser.setOnClickListener(v -> {
            searchUsers();
        });
        
        btnCompleteTask.setOnClickListener(v -> {
            if (selectedUser != null) {
                simulateTaskCompletion();
            } else {
                Toast.makeText(this, "请先选择用户", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupRecyclerView() {
        userAdapter = new UserAdapter(userList);
        rvUserList.setLayoutManager(new LinearLayoutManager(this));
        rvUserList.setAdapter(userAdapter);
    }

    private void searchUsers() {
        String searchQuery = etUserSearch.getText().toString().trim();
        List<UserInfo> filteredList = new ArrayList<>();
        
        if (TextUtils.isEmpty(searchQuery)) {
            filteredList.addAll(userList);
        } else {
            for (UserInfo user : userList) {
                if (user.getUsername().toLowerCase().contains(searchQuery.toLowerCase())) {
                    filteredList.add(user);
                }
            }
        }
        
        userAdapter.updateData(filteredList);
    }

    private void updateSelectedUserInfo(UserInfo user) {
        selectedUser = user;
        
        if (user != null) {
            tvSelectedUser.setText("用户名: " + user.getUsername());
            
            boolean isPrivilege = "true".equals(user.getExtra("is_privilege"));
            String statusText = isPrivilege ? "特权用户" : "普通用户";
            tvUserStatus.setText("状态: " + statusText);
            
            String rewardInfo;
            if (isPrivilege) {
                String taskReward = user.getExtra("task_reward");
                String inviteReward = user.getExtra("invite_reward");
                rewardInfo = "任务奖励: " + (taskReward != null ? taskReward : "未设置") + 
                             " | 邀请奖励: " + (inviteReward != null ? inviteReward : "未设置");
            } else {
                rewardInfo = "任务奖励: 全局默认 (" + globalTaskReward + 
                             ") | 邀请奖励: 全局默认 (" + globalInviteReward + ")";
            }
            tvUserRewardInfo.setText(rewardInfo);
            
            btnCompleteTask.setEnabled(true);
        } else {
            tvSelectedUser.setText("未选择用户");
            tvUserStatus.setText("状态: -");
            tvUserRewardInfo.setText("任务奖励: -");
            btnCompleteTask.setEnabled(false);
        }
    }

    private void simulateTaskCompletion() {
        if (selectedUser == null) return;
        
        // 1. 计算任务完成后该用户获得的奖励
        float taskReward = calculateTaskReward(selectedUser);
        
        // 2. 查找该用户的上级链
        List<UserInfo> parentChain = findParentChain(selectedUser);
        
        // 3. 计算各级上级获得的分成
        List<RewardDistribution> distributions = calculateDistributions(selectedUser, taskReward, parentChain);
        
        // 4. 显示模拟结果
        displaySimulationResult(selectedUser, taskReward, distributions);
        
        // 5. 更新用户余额（仅用于模拟）
        updateUserBalances(selectedUser, taskReward, distributions);
        
        // 6. 弹出成功对话框
        showSuccessDialog(taskReward);
    }

    private float calculateTaskReward(UserInfo user) {
        if (!taskRewardEnabled) {
            return 0;
        }
        
        boolean isPrivilege = "true".equals(user.getExtra("is_privilege"));
        if (isPrivilege) {
            String customReward = user.getExtra("task_reward");
            if (customReward != null && !customReward.isEmpty()) {
                try {
                    return Float.parseFloat(customReward);
                } catch (NumberFormatException e) {
                    return globalTaskReward;
                }
            }
        }
        
        return globalTaskReward;
    }

    private List<UserInfo> findParentChain(UserInfo user) {
        List<UserInfo> parentChain = new ArrayList<>();
        String parentId = user.getExtra("parent_id");
        
        for (int level = 1; level <= 3; level++) {
            if (parentId == null || parentId.isEmpty()) break;
            
            UserInfo parent = findUserById(Integer.parseInt(parentId));
            if (parent != null) {
                parentChain.add(parent);
                parentId = parent.getExtra("parent_id");
            } else {
                break;
            }
        }
        
        return parentChain;
    }

    private UserInfo findUserById(int userId) {
        for (UserInfo user : userList) {
            if (user.getId() == userId) {
                return user;
            }
        }
        return null;
    }

    private List<RewardDistribution> calculateDistributions(UserInfo user, float taskReward, List<UserInfo> parentChain) {
        List<RewardDistribution> distributions = new ArrayList<>();
        
        for (int i = 0; i < parentChain.size(); i++) {
            UserInfo parent = parentChain.get(i);
            int level = i + 1; // 1, 2, 或 3
            
            float ratio = getParentRatio(parent, level);
            float amount = taskReward * ratio / 100;
            
            if (amount > 0) {
                distributions.add(new RewardDistribution(parent, level, ratio, amount));
            }
        }
        
        return distributions;
    }

    private float getParentRatio(UserInfo parent, int level) {
        boolean isPrivilege = "true".equals(parent.getExtra("is_privilege"));
        
        if (isPrivilege) {
            String ratioKey = "level" + level + "_ratio";
            String customRatio = parent.getExtra(ratioKey);
            
            if (customRatio != null && !customRatio.isEmpty()) {
                try {
                    return Float.parseFloat(customRatio);
                } catch (NumberFormatException e) {
                    // 回退到全局比例
                }
            }
        }
        
        // 使用全局分成比例
        switch (level) {
            case 1:
                return taskL1Ratio;
            case 2:
                return taskL2Ratio;
            case 3:
                return taskL3Ratio;
            default:
                return 0;
        }
    }

    private void displaySimulationResult(UserInfo user, float taskReward, List<RewardDistribution> distributions) {
        StringBuilder result = new StringBuilder();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String currentTime = sdf.format(new Date());
        
        result.append("【模拟完成时间】").append(currentTime).append("\n\n");
        result.append("【任务完成用户】").append(user.getUsername()).append("\n");
        result.append("【获得任务奖励】").append(String.format("%.2f", taskReward)).append("\n\n");
        
        if (!distributions.isEmpty()) {
            result.append("【上级分成明细】\n");
            for (RewardDistribution dist : distributions) {
                result.append(dist.parent.getUsername())
                      .append("（").append(dist.level).append("级上级）获得 ")
                      .append(String.format("%.2f", dist.amount))
                      .append("（").append(String.format("%.1f", dist.ratio)).append("%）\n");
            }
        } else {
            result.append("【上级分成明细】无上级用户或分成比例为0\n");
        }
        
        result.append("\n【计算说明】\n");
        boolean isPrivilege = "true".equals(user.getExtra("is_privilege"));
        if (isPrivilege) {
            result.append("- ").append(user.getUsername()).append(" 是特权用户，使用特权奖励金额 ").append(String.format("%.2f", taskReward)).append("\n");
        } else {
            result.append("- ").append(user.getUsername()).append(" 是普通用户，使用全局奖励金额 ").append(String.format("%.2f", taskReward)).append("\n");
        }
        
        for (RewardDistribution dist : distributions) {
            boolean parentIsPrivilege = "true".equals(dist.parent.getExtra("is_privilege"));
            if (parentIsPrivilege) {
                result.append("- ").append(dist.parent.getUsername())
                      .append(" 是特权用户，使用特权分成比例 ").append(String.format("%.1f", dist.ratio)).append("%\n");
            } else {
                result.append("- ").append(dist.parent.getUsername())
                      .append(" 是普通用户，使用全局分成比例 ").append(String.format("%.1f", dist.ratio)).append("%\n");
            }
        }
        
        tvSimulationResult.setText(result.toString());
    }

    private void updateUserBalances(UserInfo user, float taskReward, List<RewardDistribution> distributions) {
        // 更新完成任务用户的余额
        updateUserBalance(user, taskReward);
        
        // 更新上级用户的余额
        for (RewardDistribution dist : distributions) {
            updateUserBalance(dist.parent, dist.amount);
        }
        
        // 刷新UI
        if (selectedUser != null && selectedUser.getId() == user.getId()) {
            updateSelectedUserInfo(selectedUser);
        }
    }

    private void updateUserBalance(UserInfo user, float amount) {
        String balanceStr = user.getExtra("balance");
        float balance = 0;
        if (balanceStr != null && !balanceStr.isEmpty()) {
            try {
                balance = Float.parseFloat(balanceStr);
            } catch (NumberFormatException e) {
                balance = 0;
            }
        }
        
        balance += amount;
        user.putExtra("balance", String.valueOf(balance));
    }

    private void showSuccessDialog(float reward) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("模拟成功")
               .setMessage("任务已完成，用户获得奖励 " + String.format("%.2f", reward) + "\n各级分成已计算并显示在结果区域")
               .setPositiveButton("确定", null)
               .show();
    }

    // 用户适配器
    private class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {
        private List<UserInfo> users;
        
        public UserAdapter(List<UserInfo> users) {
            this.users = new ArrayList<>(users);
        }
        
        public void updateData(List<UserInfo> newUsers) {
            this.users = new ArrayList<>(newUsers);
            notifyDataSetChanged();
        }
        
        @NonNull
        @Override
        public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user, parent, false);
            return new UserViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(@NonNull UserViewHolder holder, int position) {
            UserInfo user = users.get(position);
            holder.bind(user);
        }
        
        @Override
        public int getItemCount() {
            return users.size();
        }
        
        class UserViewHolder extends RecyclerView.ViewHolder {
            TextView tvUserName, tvUserType;
            
            public UserViewHolder(@NonNull View itemView) {
                super(itemView);
                tvUserName = itemView.findViewById(R.id.tv_user_name);
                tvUserType = itemView.findViewById(R.id.tv_user_type);
                
                itemView.setOnClickListener(v -> {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        updateSelectedUserInfo(users.get(position));
                    }
                });
            }
            
            public void bind(UserInfo user) {
                tvUserName.setText(user.getUsername());
                boolean isPrivilege = "true".equals(user.getExtra("is_privilege"));
                tvUserType.setText(isPrivilege ? "特权用户" : "普通用户");
                
                // 设置余额信息
                String balanceStr = user.getExtra("balance");
                float balance = 0;
                if (balanceStr != null && !balanceStr.isEmpty()) {
                    try {
                        balance = Float.parseFloat(balanceStr);
                        tvUserName.setText(user.getUsername() + " (余额: " + String.format("%.2f", balance) + ")");
                    } catch (NumberFormatException e) {
                        tvUserName.setText(user.getUsername());
                    }
                }
            }
        }
    }
    
    // 奖励分配模型
    private static class RewardDistribution {
        UserInfo parent;
        int level;
        float ratio;
        float amount;
        
        public RewardDistribution(UserInfo parent, int level, float ratio, float amount) {
            this.parent = parent;
            this.level = level;
            this.ratio = ratio;
            this.amount = amount;
        }
    }
} 